package com.yeskery.nut.extend.mcp;

import com.yeskery.nut.application.ServerEventContext;
import com.yeskery.nut.core.ControllerManager;
import com.yeskery.nut.core.Environment;
import com.yeskery.nut.core.Method;
import com.yeskery.nut.extend.mcp.core.Constants;
import com.yeskery.nut.extend.mcp.server.HttpMcpMessageController;
import com.yeskery.nut.extend.mcp.server.HttpMcpMessageRequestHandler;
import com.yeskery.nut.util.StringUtils;

import java.util.logging.Logger;

/**
 * 基于Http的MCP Server插件
 * @author sprout
 * 2025-04-17 10:25
 */
public class McpHttpServerPlugin extends BaseMcpServerPlugin {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(McpHttpServerPlugin.class.getName());

    @Override
    public void beforeStart(ServerEventContext serverEventContext) {
        ControllerManager controllerManager = serverEventContext.getControllerManager();
        Environment environment = getApplicationContext().getBean(Environment.class);
        String httpEndpoint = getMcpHttpEndpoint(environment);
        HttpMcpMessageRequestHandler httpMcpMessageRequestHandler = new HttpMcpMessageRequestHandler(getApplicationContext(),
                getMcpSessionManager(), getMcpServerCapability());
        controllerManager.registerController(new HttpMcpMessageController(httpMcpMessageRequestHandler), httpEndpoint);
        logger.info("MCP[Http], Endpoint[" + httpEndpoint + "], Alias[], Method[" + Method.POST + "]");
    }

    /**
     * 获取MCP HTTP Endpoint
     * @param environment 环境
     * @return MCP HTTP Endpoint
     */
    private String getMcpHttpEndpoint(Environment environment) {
        String endpoint = environment.getEnvProperty("nut.mcp.server.endpoint.http");
        return StringUtils.isEmpty(endpoint) ? Constants.DEFAULT_HTTP_ENDPOINT : endpoint;
    }
}
